<!--
* @Author: zhangjing
* @Date: 2025-06-05 14:18:26
* @Description: 抢红包=>
-->
<template>
	<div class="redpackbox">
		<audio ref="music" :src="bgAudio" crossOrigin="anonymous" preload loop></audio>
		<div class="progress" v-show="operateType == 'answer'">
			<div class="progress-bar"><div class="progress-inner" :style="{ width: rate + '%' }"></div></div>
			<div class="count">答题人数{{ answerNumber }}</div>
			<div class="count totalcount">总人数{{ totalNumber }}</div>
		</div>
		<div class="contain" :style="{ width: w }"></div>

		<div v-if="operateType == 'result'">
			<div class="imgbox">
				<div class="img-con" v-for="(item, index) in ranklist" @click="praiseStud(item)">
					<div class="imgItem" :class="['img0' + item.rank]">
						<img :src="(isPro ? '/impromptu_pro/img0' : '/impromptu/img0') + item.rank + '.png'" />
						<span class="number">{{ item.rank }}</span>
						<div class="name" :title="item.studName || ''">
							<div class="name-stuName" style="-webkit-box-orient: vertical">
								{{ item.studName || '' }}({{ item.score }}分)
							</div>
						</div>
					</div>
				</div>
			</div>
			<div class="rank">
				<div class="conbox-con">
					<div class="conbox-bd">
						<div class="list">
							<div class="item" v-for="(item, index) in allredpacklist" :key="index">
								{{ item.studName }}({{ item.score }}分)
							</div>
						</div>
					</div>
					<a href="javascript:;" class="closeWin" @click="reback"><img src="closeWin.png" alt="" /></a>
				</div>
			</div>
		</div>
		<div class="fixed-save-btn" :class="{ over: isAnswering - 0 }" @click="startAnswer">
			{{ isAnswering - 0 ? '结束' : '开始' }}
		</div>
		<a href="javascript:;" v-if="operateType == 'nostart'" class="closeWin exit" @click="reback"
			><img src="closeWin.png" alt=""
		/></a>
	</div>
</template>

<script>
import $ from '@/utils/jquery-vendor';
import { fileUrl, generateRandomString, getBytesLength } from '@/utils/base';
let num = 0;
let column = 0;
let list = [];
let timer = null,
	stimer = null;
let images = [];
function isElementInViewport(el) {
	//获取元素是否在可视区域
	var rect = el.getBoundingClientRect();
	return (
		rect.top >= 0 &&
		rect.left >= 0 &&
		rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
		rect.right <= (window.innerWidth || document.documentElement.clientWidth)
	);
}
function isVisible(selectid) {
	var o;
	if ('object' === typeof selectid) {
		o = selectid;
	} else {
		o = $(selectid);
	}
	var of = o.offset();
	var w = $(window);
	return !(w.scrollTop() > of.top + o.outerHeight() - 200 || w.scrollTop() + w.height() * 0.8 < of.top);
}
function addredenvelope(info) {
	const win = parseInt($('.contain').css('width'));
	$('.contain').css({
		opacity: 1,
	});
	var hb = parseInt(Math.random() * (3 - 1) + 1);
	var Wh = parseInt(Math.random() * (70 - 30) + 20);
	var Left = parseInt(Math.random() * column);
	let redtype = parseInt(Math.floor(Math.random() * 3) + 1);
	var rot = parseInt(Math.random() * 360) + 'deg';
	var time = new Date().getTime();
	var deybottom = 0;
	if (list[Left] && $('#li' + list[Left]).length > 0) {
		try {
			var reg = /matrix.((.+([, ]+)?){6})./g;
			var str = $('#li' + list[Left]).css('transform');
			// console.log(str);
			var arr = reg.exec(str);
			var newarr = arr[1].split(/[, ]+/g);
			// console.log(newarr[5]);
			var leftbottom = parseFloat(newarr[5]);
			if (leftbottom < 0) {
				var oldflytypehight =
					parseInt($('#li' + list[Left]).css('height')) < 160
						? 160
						: parseInt($('.li' + this.list[Left]).css('height'));
				// deybottom = leftbottom - oldflytypehight;
				deybottom = leftbottom * -1;
			}
		} catch (e) {
			//TODO handle the exception
		}
	}
	list[Left] = time;
	$('.contain').append(
		"<div id='li" + time + "' class='redpack redpack" + redtype + "' ><a href='javascript:;'></a></div>"
	);
	var startHeight = ($('#li' + time).height() + deybottom + 40) * -1; //初始位置
	$('#li' + time).css({
		left: Left * 140,
		'-webkit-transform': 'translateY(' + startHeight + 'px)',
		transform: 'translateY(' + startHeight + 'px)',
	});
	let speed = 1 / $('.contain').height(); //速度
	var stopHeight = $('.contain').height() + 20; //最后隐藏的位置
	let rate = (stopHeight - startHeight) * speed; //匀速所需要的的时间
	$('#li' + time).css({
		'-webkit-transform': 'translateY(' + stopHeight + 'px)',
		transform: 'translateY(' + stopHeight + 'px)',
		'-webkit-transition-duration': rate * 2 + 's',
		'transition-duration': rate * 2 + 's',
		'transition-timing-function': 'linear',
		'-webkit-transition-timing-function': 'linear',
	});
	$('#li' + time).on('transitionend webkitTransitionEnd', function () {
		$(this).remove();
	});
}

function borad(info, score, stuName, profilePicture) {
	var time = new Date().getTime();
	$('.contain').append(
		"<div class='prizebox" +
			time +
			" prizebox' style='left:" +
			(parseInt(info.left) + 70) +
			'px;top:' +
			(info.top - 40) +
			"px;'><div class='num'><i></i><span>+" +
			score +
			"</span></div><div class='imgbox' " +
			(profilePicture ? "style='background-image: url(" + fileUrl + profilePicture + ")'" : '') +
			" ></div><div class='name'>" +
			stuName +
			'</div></div>'
	);
	$('.prizebox' + time).on('animationEnd webkitAnimationEnd', function () {
		$(this).remove();
	});
}
function getRandomNumber(min, max) {
	return Math.floor(Math.random() * (max - min + 1)) + min;
}
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex';
export default {
	data() {
		return {
			w: '100px',
			redpacklist: [],
			allredpacklist: [],
			column: 1,
			bgAudio: '/redpack/mp3/bg.mp3', //抢红包背景音乐
			answerNumber: 0,
			operateType: 'nostart',
			ranklist: [],
		};
	},
	props: {
		//接收器信息
		machineData: {
			type: Object,
			default: () => {},
		},
		//表单数据
		formData: {
			type: Object,
			default: () => {},
		},
	},
	created() {
		let w = document.body.offsetWidth * 0.8;
		this.w = w - (w % 140) + 'px';
		this.column = (w - (w % 140)) / 140;
		column = this.column;
	},
	mounted() {
		this.creatAns();
		let redpackId = this.$ls.get('redpackId') || '';
		if (redpackId && this.isAnswering - 0) {
			this.operateType = 'answer';
			this.getScore();
		}
	},
	computed: {
		...mapState({
			deviceType: (state) => state.websockStore.deviceType,
			studentList: (state) => state.websockStore.studentList,
			isPro: (state) => state.isPro,
			stopDeviceEventList: (state) => state.websockStore.stopDeviceEventList,
			minProjectLogin: (state) => state.minProjectStore.minProjectLogin, //小程序是否登录
			isAnswering: (state) => state.websockStore.isAnswering,
		}),
		wiredAnswer() {
			return this.$store.getters.onEvent('wiredanswer');
		},
		totalNumber() {
			let num = 0;
			if (this.studentList && this.studentList.length > 0) {
				num = this.studentList.filter((item) => item.status == 1).length;
			}
			return num;
		},
		rate() {
			if (this.totalNumber) {
				return (this.answerNumber / this.totalNumber) * 100;
			}
			return 0;
		},
	},
	watch: {
		//有线设备上报答题数据
		wiredAnswer: {
			handler(newValue, oldValue) {
				if (newValue && newValue != oldValue) {
					let uID = newValue.uID - 0;
					let stuInfo = this.studentList.find((item) => item.machineId - 0 == uID);
					this.ans_id = sessionStorage.getItem('ans_id');
					if (this.ans_id && this.ans_id == newValue.ans_id && newValue.ans_str == 'G') {
						this.curuID = uID;
						let info = this.studentList.find((item) => item.machineId - 0 == uID);
						if (!!info) {
							let score = getRandomNumber(1, 10);
							this.addredpack({
								...info,
								score,
							});
							let msg = '   ' + info.studName;
							let len = 16 - getBytesLength(msg);
							for (var i = 0; i < len; i++) {
								msg = msg + ' ';
							}
							msg = msg + '  ';

							if (info.machineId - 0 == uID) {
								msg = msg + ' 获得' + score + '积分';
							}
							this.answerNumber++;
							this.WEBSOCKET_SEND({
								fun: 'dtq_echo_set',
								uID: info.machineId - 0,
								msg: msg,
							});
						}
					}
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
	},

	destroyed() {
		if (timer) {
			clearInterval(timer);
		}
		if (stimer) {
			clearInterval(stimer);
		}
	},
	methods: {
		...mapMutations(['WEBSOCKET_SEND', 'SET_isAnswering', 'SET_ANS_ID']),
		addredpack(info) {
			console.log('抢红包', info);
			this.redpacklist.push(info);
			this.allredpacklist.push(info);
		},
		//去答题
		startAnswer() {
			if (this.isAnswering - 0) {
				this.stopAnswer();
				return;
			}
			/* 判断移动端正在控制PC端 */
			/*if (this.minProjectLogin) {
				this.$message.error('移动端正在控制PC端，不能发题！');
				return;
			}*/
			//发题前判断该班级是否有学生。
			if (this.studentList.length == 0) {
				let tempTestData = this.$ls.get('tempTestData');
				this.$message.error('（' + tempTestData.className + '）班级没有学生，请先添加学生！');
				return;
			}
			this.redpacklist = [];
			this.answerNumber = 0;
			this.allredpacklist = [];
			if (!timer) {
				this.creatAns();
			}
			this.getScore();
			this.sendStartAnswer();
		},
		creatAns() {
			timer = setInterval(() => {
				addredenvelope(0);
			}, 300);
			addredenvelope(0);
			this.$nextTick(() => {
				this.$refs.music.play();
			});
		},
		getScore() {
			stimer = setInterval(() => {
				let size = $('.contain .redpack').length;
				let list = [];
				for (var i = 0; i < size; i++) {
					let $item = $('.contain .redpack').eq(i);
					if (isVisible($item)) {
						list.push($item);
					}
				}
				if (list.length > 0 && this.redpacklist.length > 0) {
					let info = this.redpacklist.shift();
					let $me = list[parseInt(Math.random() * list.length)];
					borad(
						{
							left: $me.css('left'),
							top: $me.offset().top,
						},
						info.score,
						info.studName
					);
					$me.remove();
				}
			}, 100);
		},
		sendStartAnswer() {
			this.$ls.set('redpackId', generateRandomString());
			this.WEBSOCKET_SEND({
				fun: 'answer_start',
				uID: 0,
				type: 3,
			});
			this.studentList.forEach((item) => {
				console.log('item', item);
				if (item.status == 1) {
					let msg = '   ' + item.studName;
					let len = 16 - getBytesLength(msg);
					for (var i = 0; i < len; i++) {
						msg = msg + ' ';
					}
					msg = msg + '   请按键语音键';
					this.WEBSOCKET_SEND({
						fun: 'dtq_echo_set',
						uID: item.machineId - 0,
						msg: msg,
					});
				}
			});
			this.operateType = 'answer';
			this.SET_isAnswering(1);
		},
		stopAnswer() {
			this.WEBSOCKET_SEND({
				fun: 'answer_start',
				uID: 0,
				type: 128, //结束答题
			});
			this.redpacklist = [];
			this.answerNumber = 0;
			this.operateType = 'result';
			this.SET_isAnswering(0);
			this.SET_ANS_ID('');
			this.$ls.remove('redpackId');
			this.studentList.forEach((item) => {
				if (item.status == 1) {
					let msg = '   ' + item.studName;
					this.WEBSOCKET_SEND({
						fun: 'dtq_echo_set',
						uID: item.machineId - 0,
						msg: msg,
					});
				}
			});
			if (timer) {
				clearInterval(timer);
				timer = null;
			}
			if (stimer) {
				clearInterval(stimer);
				stimer = null;
			}
			if (this.$refs.music) {
				this.$refs.music.pause();
				this.$refs.music.currentTime = 0;
			}
			let allredpacklist = [...this.allredpacklist];
			allredpacklist.sort((a, b) => {
				return b.score - a.score;
			});
			this.allredpacklist = [...allredpacklist];
			let ranklist = this.allredpacklist.slice(0, 5);
			let rank = 1;
			ranklist.forEach((item, index) => {
				if (index > 0 && item.score < ranklist[index - 1].score) {
					rank = index + 1;
				}
				item.rank = rank;
			});
			this.ranklist = [...ranklist];
		},
		//返回
		reback() {
			this.$emit('checkMenu', { type: 'redpack' });
		},
	},
};
</script>
<style lang="less" scoped>
.fixed-save-btn {
	background: @primary-color;
	width: 300px;
	height: 60px;
	line-height: 60px;
	border-radius: 40px;
	text-align: center;
	color: #fff;
	font-size: 30px;
	font-weight: bold;
	cursor: pointer;
	position: fixed;
	bottom: 60px;
	left: 50%;
	transform: translateX(-50%);
	z-index: 9;
	&.over {
		background: @warning-color;
	}
}

.conbox-con {
	height: 100%;
	border-radius: 8px;
	background: transparent;
	z-index: 6;
	position: relative;
}
.closeWin {
	position: absolute;
	right: -20px;
	bottom: -16px;
	width: 46px;
	height: 46px;
	img {
		display: block;
		width: 100%;
		height: 100%;
	}
	&.exit {
		bottom: 60px;
		left: 50%;
		transform: translateX(300px);
	}
}
.conbox-hd {
	font-size: 22px;
	color: #2e2424;
	text-align: center;
	position: relative;
	margin-bottom: 20px;
	margin-top: 0;
}

.conbox-bd {
	width: 1162px;
	height: calc(100vh - 400px);
	margin: 0 auto 27px;
	background: rgb(243, 248, 255);
	border: 2px solid @primary-color;
	border-radius: 10px;
	overflow: hidden;
	position: relative;

	.list {
		margin: 20px;
		background: rgb(255, 255, 255);
		border: 2px dashed @primary-color;
		border-radius: 10px;
		height: calc(100% - 40px);
		font-size: 20px;
		color: #2e2424;
		padding: 20px 62px 40px;
		overflow: auto;
		text-align: left;
		.item {
			width: 25%;
			display: inline-block;
			cursor: pointer;
			text-align: left;
			margin-bottom: 30px;
			.name {
				//margin-right: 18px;
				width: 5em;
				display: inline-block;
				text-align: left;
				word-break: break-all;
				vertical-align: middle;
				margin-right: 10px;
			}

			.number {
				display: inline-block;
				width: 12em;
				text-align: left;
				vertical-align: middle;
			}
		}
	}
}
/***排名***/
.rank {
	text-align: center;
	width: 1162px;
	margin: 250px auto 0;
	// padding: 50px 0 30px;
	@media screen and (max-width: 1366px) {
		width: 1024px;
	}
}

.imgbox {
	position: fixed;
	top: 80px;
	left: 50%;
	transform: translateX(-50%);
	// height: 199px;
	display: flex;

	.img-con {
		height: 157px;
		display: inline-block;
		position: relative;
		display: flex;
		align-items: flex-end;
		cursor: pointer;
	}

	.imgItem {
		position: absolute;
		bottom: 0;
		display: inline-block;
		margin: 0 20px;
		position: relative;
		text-align: center;

		img {
			width: 100%;
			height: 100%;
			/* position: absolute;
					bottom: 0; */
		}

		.number {
			position: absolute;
			top: 0;
			left: 50%;
			transform: translate(-50%);
			color: #fff;
			font-weight: bold;
		}

		.name {
			width: 100%;
			position: absolute;
			bottom: 11px;
			text-align: center !important;
			color: #fff;
			font-weight: bold;
			.name-stuName {
				padding: 0 0 7px;
				text-align: center !important;
				white-space: nowrap;
			}
		}

		&.img01 {
			//width: 231px;
			width: 181px;
			font-size: 26px;

			.number {
				top: 2%;
				font-size: 60px;
			}
			.name-stuName {
				line-height: 30px;
			}
		}

		&.img02 {
			//width: 198px;
			width: 148px;
			font-size: 24px;

			.number {
				top: 5%;
				font-size: 50px;
			}

			.name {
				bottom: 8px;
			}
			.name-stuName {
				line-height: 28px;
			}
		}

		&.img03 {
			//width: 178px;
			width: 128px;
			font-size: 22px;

			.number {
				top: 8%;
				font-size: 40px;
			}

			.name {
				bottom: 5px;
			}
			.name-stuName {
				line-height: 26px;
			}
		}

		&.img04 {
			//width: 131px;
			width: 110px;
			font-size: 18px;

			.number {
				top: 9%;
				font-size: 32px;
			}

			.name {
				bottom: 7px;
			}
			.name-stuName {
				line-height: 18px;
			}
		}

		&.img05 {
			width: 96px;
			//width: 66px;
			font-size: 16px;

			.number {
				font-size: 30px;
				top: 8%;
			}

			.name {
				bottom: 5px;
			}
			.name-stuName {
				line-height: 16px;
			}
		}
	}
	@media screen and (max-width: 1366px) {
		position: fixed;
		top: 40px;
		.imgItem {
			&.img01 {
				width: 141px;
				font-size: 26px;

				.number {
					top: 2%;
					font-size: 50px;
				}
				.name {
					bottom: 6px;
				}
			}

			&.img02 {
				//width: 198px;
				width: 148px;
				font-size: 24px;

				.number {
					top: 5%;
					font-size: 50px;
				}

				.name {
					bottom: 8px;
				}
			}

			&.img03 {
				//width: 178px;
				width: 128px;
				font-size: 22px;

				.number {
					top: 8%;
					font-size: 40px;
				}

				.name {
					bottom: 5px;
				}
			}

			&.img04 {
				//width: 131px;
				width: 110px;
				font-size: 14px;

				.number {
					top: 9%;
					font-size: 32px;
				}

				.name {
					bottom: 7px;
				}
			}

			&.img05 {
				width: 96px;
				//width: 66px;
				font-size: 12px;

				.number {
					font-size: 30px;
					top: 8%;
				}

				.name {
					bottom: 5px;
				}
			}
		}
	}
}
</style>
<style lang="less">
.redpackbox {
	position: fixed;
	top: 0;
	left: 0;
	bottom: 0;
	right: 0;
	background: url(/redpack/redpackbg.jpg) no-repeat center bottom;
	.progress {
		position: fixed;
		top: 75px;
		left: 50%;
		transform: translateX(-50%);
		.progress-bar {
			width: 697px;
			height: 44px;
			background: #fff;
			border: 10px solid #607b34;
			border-radius: 2000px;
			.progress-inner {
				width: 10%;
				height: 24px;
				background: linear-gradient(180deg, #dbefbc 0%, #dbefbc 0%, #85a550 100%);
				border-radius: 2000px;
				position: relative;
				transform: all 0.3s;
				&::before {
					content: '';
					display: block;
					height: 7px;
					width: 11px;
					background: url(/redpack/proicon2.png) no-repeat;
					position: absolute;
					left: 3px;
					top: 16px;
				}
				&::after {
					content: '';
					display: block;
					height: 107px;
					width: 107px;
					background: url(/redpack/proicon1.png) no-repeat center center;
					position: absolute;
					right: -50px;
					top: 50%;
					transform: translateY(-50%);
				}
			}
		}
		.count {
			width: 78px;
			height: 35px;
			background: #fabe01;
			border: 4px solid #607b34;
			color: #fff;
			text-align: center;
			line-height: 25px;
			font-size: 12px;
			border-radius: 10px;
			padding: 0 6px;
			position: absolute;
			top: -47px;
			&::after,
			&::before {
				content: '';
				display: block;
				width: 0;
				height: 0;
				position: absolute;
				border-top: 7px solid #607b34;
				border-left: 4px solid transparent;
				border-right: 4px solid transparent;
				left: 50%;
				transform: translateX(-50%);
			}
			&::after {
				top: 31px;
			}
			&::before {
				border-top: 5px solid #fabe01;
				border-left: 2px solid transparent;
				border-right: 2px solid transparent;
				top: 27px;
			}
			&.totalcount {
				right: 0;
			}
		}
	}

	.contain {
		position: absolute;
		top: 0;
		bottom: 0;
		left: 50%;
		// border: 1px solid #f00;
		transform: translate(-50%);
		.redpack {
			width: 140px;
			height: 140px;
			position: absolute;
			top: 0;
			background: no-repeat center center;
			&.redpack1 {
				background-image: url(/redpack/redpack1.png);
			}
			&.redpack2 {
				background-image: url(/redpack/redpack2.png);
			}
			&.redpack3 {
				background-image: url(/redpack/redpack3.png);
			}
		}

		.prizebox {
			position: absolute;
			top: 50%;
			width: 298px;
			height: 287px;
			background: url(/redpack/avatar/redpackbg.png) no-repeat center center;
			padding-top: 40px;
			opacity: 0;
			animation: 2.5s 0s fadeOutUp;
			transform-origin: 50% 50%;
			-webkit-transform: scale3d(0.3, 0.3, 0.3) translate3d(-50%, 0, 0);
			transform: scale3d(0.3, 0.3, 0.3) translate3d(-50%, 0, 0);
		}
		.prizebox .imgbox {
			width: 126px;
			height: 126px;
			// border: 2px solid #f00;
			border-radius: 100%;
			overflow: hidden;
			margin: 0 auto;
			background: #fffcda url(/redpack/avatar/5.jpg) no-repeat center center;
			background-size: cover;
			position: absolute;
			top: 92px;
			transform: translateX(-50%);
			left: 50%;
		}
		// .prizebox .imgbox img {
		//   display: block;
		//   width: 95px;
		//   margin: 0 auto;
		// }
		.prizebox .name {
			position: absolute;
			bottom: 29px;
			padding-top: 8px;
			color: #fff;
			font-size: 26px;
			font-weight: bold;
			text-align: center;
			line-height: 32px;
			width: 198px;
			height: 61px;
			transform: translateX(-50%);
			left: 50%;
			text-shadow: 0 4px 0 rgba(126, 84, 1, 1);
			background: url(/redpack/avatar/namebg.png) no-repeat center center;
			background-size: cover;
		}
		.prizebox .num {
			color: #fff;
			background: #e52946;
			border: 2px solid #ffc812;
			border-radius: 50px;
			line-height: 38px;
			height: 42px;
			padding: 0 20px;
			top: 30px;
			left: 50%;
			font-size: 24px;
			transform: translateX(-50%);
			position: absolute;
		}
		.prizebox .num i {
			display: inline-block;
			height: 32px;
			width: 32px;
			vertical-align: -0.25em;
			background: url(/redpack/avatar/star2.png);
			background-size: cover;
		}
	}
}
</style>
<style></style>
